<template>
  <div v-loading="loading">
    <div class="h12" />
    <el-card>
      <el-tabs v-model="activeName" type="card" @tab-click="showActions">
        <el-tab-pane label="设备控制" name="first">
          <div class="action-container">
            <el-row>
              <div v-for="(item, index) in rtuActionDisplays" :key="index">
                <el-col
                  v-if="item.action_type == 'select'"
                  :span="8"
                  style="margin: 8px 0"
                >
                  <div class="action-board">
                    <b style="width: 100px; font-size: 14px">
                      {{ item.name }}：
                    </b>
                    <el-button-group>
                      <el-button
                        v-for="(citem, cindex) in item.action_arr"
                        :key="cindex"
                        :type="getButtonType(item, cindex)"
                        @click="sendCommand(citem, item)"
                      >
                        {{ citem.name }}
                      </el-button>
                    </el-button-group>
                  </div>
                </el-col>
                <el-col
                  v-else
                  :span="24"
                  style="display: flex; align-items: center; margin: 6px 0"
                >
                  <b style="width: 100px; font-size: 14px; text-align: right">
                    {{ item.name }}：
                  </b>
                  <span style="width: 80%; margin-left: 12px">
                    <el-slider
                      v-model="sliderValue"
                      show-input
                      @change="changeSlider(item)"
                    />
                  </span>
                </el-col>
              </div>
            </el-row>
          </div>
        </el-tab-pane>
        <el-tab-pane label="操作履历" name="second">
          <el-empty v-if="actionDays.length === 0" description="暂无记录" />
          <el-tabs v-else :tab-position="tabPosition" @tab-click="handleClick">
            <el-tab-pane
              v-for="(item, index) in actionDays"
              :key="index"
              v-loading="loading"
              :label="item"
            >
              <div class="h12" />
              <el-radio-group v-model="reverse" style="margin-left: 40px">
                <el-radio :label="true">倒序</el-radio>
                <el-radio :label="false">正序</el-radio>
              </el-radio-group>
              <div class="h12" />
              <div
                style="
                  max-height: 480px;
                  padding: 10px 0 0 0;
                  overflow-y: scroll;
                "
              >
                <el-timeline :reverse="reverse">
                  <el-timeline-item
                    v-for="(citem, cindex) in actions"
                    :key="cindex"
                    placement="top"
                    :timestamp="citem.time"
                  >
                    <div>
                      <div class="h12" />
                      <div>
                        <span class="mr12">{{ citem.name }}</span>
                        <b :class="getClass(citem.action)">
                          {{ citem.action }}
                        </b>
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
  import { sendCommand } from '@/api/device'
  import { getActions, getActionDays } from '@/api/device'
  export default {
    props: {
      device: {
        type: Object,
        default() {
          return {}
        },
      },
    },
    data() {
      return {
        activeName: 'first',
        actionDays: [],
        searchDate: '',
        current: 0,
        page: 1,
        pages: 1,
        reverse: true,
        actions: [],
        loading: false,
        tabPosition: 'left',
        sliderValue: 0,
        rtuActionDisplays: [],
        states: {},
      }
    },
    computed: {
      actionListener() {
        const serialno = this.device.serialno
        const activeName = this.activeName
        return { serialno, activeName }
      },
    },
    watch: {
      device: {
        handler(newVal) {
          const rtuActionDisplays =
            (newVal &&
              (newVal.rtuActionDisplays || newVal.rtu_action_displays)) ||
            []
          if (rtuActionDisplays.length > 0) {
            this.rtuActionDisplays = rtuActionDisplays
            this.rtuActionDisplays.map((val) => {
              if (typeof val.action_arr === 'string') {
                val.action_arr = JSON.parse(val.action_arr)
              }
            })
            if (newVal.states && newVal.states.REG_HMI_PWM) {
              this.sliderValue = Number(newVal.states.REG_HMI_PWM)
            }
          }
        },
        deep: true,
        immediate: true,
      },
      searchDate: {
        handler(newVal) {
          if (newVal) {
            this.actions = []
            this.getActions()
          }
        },
        immediate: true,
      },
    },
    methods: {
      showActions(val) {
        if (val.name === 'second') {
          this.getActionDays()
          if (this.searchDate) {
            this.getActions()
          }
        }
      },
      resetActive() {
        this.activeName = 'first'
        // this.searchDate = ''
        this.actionDays = []
      },
      async getActionDays() {
        const { data } = await getActionDays(this.device.serialno)
        this.actionDays = data
        this.searchDate = this.actionDays[this.current]
      },
      async getActions() {
        this.loading = true
        const { data } = await getActions({
          serialno: this.device.serialno,
          time: this.searchDate,
          page: this.page,
          pageSize: 100,
        })
        this.loading = false
        this.convertData(data)
      },
      handleClick(e) {
        this.searchDate = e.label
      },
      getClass(action) {
        if (action.indexOf('开') > -1 || action.indexOf('启动') > -1) {
          return 'color-success'
        }
        if (action.indexOf('关') > -1 || action.indexOf('停止') > -1) {
          return 'color-danger'
        }
        return ''
      },
      convertData(data) {
        this.actions = this.actions.concat(data.data)
        this.page = data.current_page
        this.pages = data.last_page
      },
      sendCommand(item, pitem) {
        this.$confirm('确定要进行此操作吗？', '操作确认', {
          type: 'warning',
        }).then(() => {
          if (Array.isArray(item.namekey)) {
            item.namekey.forEach((val) => {
              const data = {
                namekey: val,
                params: item.params,
              }
              this._sendCommand(data, pitem)
            })
          } else {
            const data = {
              namekey: item.namekey,
              value: item.params,
            }
            this._sendCommand(data, pitem)
          }
        })
      },
      async _sendCommand(data, item) {
        this.loading = true
        const serialno = item.rtu_serialno || this.device.serialno
        const { msg } = await sendCommand(data, serialno).catch((err) => {
          console.log(err)
          this.loading = false
        })
        this.loading = false
        this.$message({ message: msg, type: 'success', showClose: true })
      },
      changeSlider(item) {
        const sliderValue = Number(this.sliderValue)
        this.$confirm(
          `确定要将行进速率设置为 ${sliderValue}% 吗？`,
          '操作确认',
          { type: 'info' }
        ).then(() => {
          const data = {
            namekey: item.action_arr[0].namekey,
            value: 256 + sliderValue,
          }
          this._sendCommand(data, item)
        })
      },
      getButtonType(item, cindex) {
        console.log(item, cindex)
        return 'default'
      },
    },
  }
</script>

<style lang="scss" scoped>
  .action-board {
    b {
      display: inline-block;
      width: 100px;
      text-align: right;
    }
  }
</style>
